package com.example.springbootdemo.bean;

import com.alibaba.fastjson.JSON;
import com.example.springbootdemo.config.GlobalVariables;
import com.example.springbootdemo.config.JHConfig;
import com.example.springbootdemo.response.ApiResponse;
import com.example.springbootdemo.response.SecretResponse;
import com.example.springbootdemo.utils.Md5Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class ApiKeyContext {
    @Autowired
    JHConfig jhConfig;

    //应用密钥获取刷新和请求密钥
    public static String GET_SECRET_BY_APPSECRET ="/egovProject/egovApi/getSecretByAppSecret.shtml";

    //根据刷新秘钥获取刷新秘钥和请求秘钥
    public static String GET_SECRET_BY_REFRESHSECRET ="/egovProject/egovApi/getSecretByRefreshSecret.shtml";

    private RestTemplate restTemplate = new RestTemplate();

   private final GlobalVariables globalVariables;

    @Autowired
    public ApiKeyContext(GlobalVariables globalVariables) {
        this.globalVariables = globalVariables;
    }

    public void updateApiKey() {
        log.warn("执行了刷新密钥接口");
        // 从接口获取新密钥的逻辑
        String url=jhConfig.getUrl()+GET_SECRET_BY_APPSECRET;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("appId", jhConfig.getAppId());
        long timeMillis = System.currentTimeMillis();
        params.add("requestTime", timeMillis + "");
        //用MD5加密的字符串(字母全部小写)， MD5 (系统应用ID+应用秘钥+发出请求时时间戳)
        String token = Md5Utils.hash(jhConfig.getAppId() + jhConfig.getAppSecret() + timeMillis);
        params.add("token", token);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);

        //请求接口
        try {
            ApiResponse apiResponse = restTemplate.postForObject(url, requestEntity, ApiResponse.class);
            if (null != apiResponse) {
                if (apiResponse.getSuccess() && "200".equals(apiResponse.getStatus())) {
                    //保存到redis
                    SecretResponse secretResponse = JSON.parseObject(JSON.toJSONString(apiResponse.getData()), SecretResponse.class);
                    String requestSecret = secretResponse.getRequestSecret();
                    String refreshSecret = secretResponse.getRefreshSecret();
                    // 更新 ThreadLocal 中的值
                    globalVariables.setApiSecret(requestSecret);
                    globalVariables.setApiRefreshSecret(refreshSecret);
                }else {
                    log.error("获取密钥异常，错误信息{}",apiResponse.getMsg());
                }
            }
        } catch (RestClientException e) {
            log.error("通过应用密钥获取刷新秘钥和请求秘钥--定时任务异常：{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 刷新token
     * 13分钟执行一次
     * 本地开发关闭避免报错，线上打开，定时刷新
     */
    @Scheduled(fixedRate = 13 * 60 * 1000)
    private void refreshSecret() {
        try {
            log.warn("执行了刷新密钥");
            System.out.println(globalVariables.getApiSecret());

           String refreshSecret =  globalVariables.getApiRefreshSecret();
            if (StringUtils.isNotBlank(refreshSecret)) {
                //请求地址
                String url = jhConfig.getUrl() + GET_SECRET_BY_REFRESHSECRET;
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
                MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
                params.add("appId", jhConfig.getAppId());
                long timeMillis = System.currentTimeMillis();
                params.add("requestTime", timeMillis + "");
                //用MD5加密的字符串(字母全部小写)， MD5 (系统应用ID+应用秘钥+发出请求时时间戳)
                String token = Md5Utils.hash(jhConfig.getAppId() + refreshSecret + timeMillis);
                params.add("token", token);
                HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);

                //请求接口
                ApiResponse apiResponse = restTemplate.postForObject(url, requestEntity, ApiResponse.class, headers);
                if (null != apiResponse) {
                    if (apiResponse.getSuccess() && "200".equals(apiResponse.getStatus())) {
                        SecretResponse secretResponse = JSON.parseObject(JSON.toJSONString(apiResponse.getData()), SecretResponse.class);
                        globalVariables.setApiSecret(secretResponse.getRequestSecret());
                        globalVariables.setApiRefreshSecret(secretResponse.getRefreshSecret());
                    }
                }else {
                    log.error("获取刷新密钥失败，错误信息{}",apiResponse.getMsg());
                }
            }
//            }
        } catch (Exception e) {
            log.error("根据刷新秘钥获取刷新秘钥和请求秘钥--定时任务异常：{}", e.getMessage());
        }
    }

}
